package com.kaibes.web.admin;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestAttribute;

import com.kaibes.core.base.util.ListUtils;
import com.kaibes.core.base.util.StringUtils;
import com.kaibes.web.permission.PermissionChecker;

@ControllerAdvice(annotations = AdminController.class)
public class AdminControllerAdvice {
    
    @Autowired
    private AdminMenuConfig adminMenuConfig;
    @Autowired
    private PermissionChecker permissionChecker;
    
    @ModelAttribute("AdminMenuUtils")
    public Class<AdminMenuUtils> base() {
        return AdminMenuUtils.class;
    }
    
    @ModelAttribute("adminMenuList")
    public List<AdminMenu> leftMenuList(@RequestAttribute(required = false) Integer userId) {
        if (userId == null) {
            return adminMenuConfig.getAdminMenus();
        } else {
            return filter(userId, ListUtils.deepCopy(adminMenuConfig.getAdminMenus()));
        }
    }
    
    @ModelAttribute
    public void currentMenu(@RequestAttribute(required = false) Integer userId, Model model, HttpServletRequest request) {
        AdminMenu currentMenu = AdminMenuUtils.findByHref(adminMenuConfig.getAdminMenus(), request.getRequestURI());
        if (currentMenu == null) {
            String uri = request.getRequestURI();
            uri = uri.substring(0, uri.lastIndexOf("/"));
            currentMenu = AdminMenuUtils.findByHref(adminMenuConfig.getAdminMenus(), uri);
        }
        if (currentMenu != null) {
            model.addAttribute("currentMenu", currentMenu);
        }
    }
    
    private List<AdminMenu> filter(Integer userId, List<AdminMenu> list) {
        Iterator<AdminMenu> iterator = list.iterator();
        while (iterator.hasNext()) {
            AdminMenu adminMenu = iterator.next();
            if (StringUtils.isBlank(adminMenu.getHref())) {
                filter(userId, adminMenu.getMenuList());
                if (adminMenu.getMenuList().isEmpty()) {
                    iterator.remove();
                }
            } else {
                if (!permissionChecker.hasPermissionGet(userId, adminMenu.getHref())) {
                    iterator.remove();
                }
            }
        }
        return list;
    }
    
}
